<?php
namespace Home\Controller;
use Think\Controller;
class WechatController extends Controller {
    public function login()
    {
        $appid = C("weixin.appId");
        $secret = C("weixin.appSecret");
        $code = I("get.code", "");
        if(empty($code)){
            $redirect_uri = "http://sylm.xunshengkj.com/index.php/index/login/";
            $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect";
            header("location:".$url);
        } else {
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
            $data = file_get_contents($url);
            $data = json_decode($data, true);
            $access_token = $data['access_token'];
            $openid = $data['openid'];
            if(!$openid){
                $this->redirect("index/login");
            }

            //获取微信用用户信息
            $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid";
            $data = file_get_contents($url);
            $data = json_decode($data, true);

            $user = M("weixin")->where("openid='".$openid."'")->find();
            $safeInfo = array(
                'openid' => $openid,
                'nickname' => $data['nickname'],
                'sex' => $data['sex'],
                'city' => $data['city'],
                'province' => $data['province'],
                'country' => $data['country'],
                'headimgurl' => $data['headimgurl']
            );

            if(!$user){
                $safeInfo['addtime'] = time();
                $user_id = M("weixin")->add($safeInfo);
                session("user_id", $user_id);
            }else{
                M("weixin")->where("openid='".$openid."'")->save($safeInfo);
                session("user_id", $user['id']);
            }

            $this->redirect(U("Index/index"));
        }

    }

    public function jssdk_share(){
        vendor("Jssdk.jssdk");
        $appId = C("jssdk.appId");
        $appSecret = C("jssdk.appSecret");
        $jssdk = new \JSSDK($appId, $appSecret);
        $signPackage = $jssdk->GetSignPackage();

        $this->assign('signPackage',$signPackage);
    }
}